package com.sgb.merchant.view.activity;

import android.content.res.ColorStateList;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.android.material.tabs.TabLayout;
import com.im.immodel.IMUtils;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.LoginEvents;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.merchant.IndustryDetailEntity;
import com.sgb.link.router.PathLogin;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.router.PathUser;
import com.sgb.link.view.widget.CustomXTabLayout;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivityIndustryDetailBinding;
import com.sgb.merchant.view.fragment.IndustryDynamicFragment;
import com.sgb.merchant.view.fragment.IndustryInfoFragment;
import com.sgb.merchant.view.fragment.IndustryRequireFragment;
import com.sgb.merchant.viewmodel.IndustryViewModel;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @author: 王彬臣
 * @date: 2021/10/13
 * @Description: 首页-产业园区详情
 */
@Route(path = PathMerchant.IndustryDetailActivity)
public class IndustryDetailActivity extends BaseActivity<IndustryViewModel, MerchantActivityIndustryDetailBinding> {

    @Autowired(name = RouterKey.NO,desc = "详情no")
    String no;



    private String[] titles = {"园区基本信息", "园区动态", "园区入驻要求"};
    private final Fragment[] mFragment = new Fragment[3];
    private int currentIndex=0;
    private FragmentManager fragmentManager;
    IndustryInfoFragment mInfoFrag;
    IndustryDynamicFragment dynamicFragment;
    IndustryRequireFragment industryRequireFragment;
    private int id;
    IndustryDetailEntity mEntity;
    boolean isFouse;


    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_industry_detail;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(IndustryViewModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.setClick(this);
        mBinding.includeTitle.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mBinding.includeTitle.titleView.setText("产业园区详情");
        //取消tab点击效果
        mBinding.tablayout.setTabRippleColor(ColorStateList.valueOf(getResources().getColor(R.color.transparent)));
        for (String title : titles) {
            mBinding.tablayout.addTab(mBinding.tablayout.newTab().setText(title));
        }
        mBinding.tablayout.addOnTabSelectedListener(new CustomXTabLayout.SimpleSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                displayFrg(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        initData();

    }

    private void initData() {


        DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
        mViewModel.getDetail(no);
        mViewModel.ldInfo.observe(this,data->{
            mEntity=data;
            if(mEntity!=null) {
                initFragment();
                mBinding.bidLayout.setVisibility(View.VISIBLE);
                mBinding.coordinator.setVisibility(View.VISIBLE);
                if (data.getFollowNo() != 0) {
                    isFouse = true;
                    mBinding.imageUserFocus.setImageResource(R.mipmap.merchant_icon_yiguanzhu);
                    mBinding.tvUserFocus.setText("已关注");
                    mBinding.tvUserFocus.setTextColor(getResources().getColor(R.color.color_secondary_red));
                }
                mBinding.setViewModel(mEntity);
            }


        });
        mViewModel.ldState.observe(this,state->{
            switch (state){//0未上架 1已删除 2正常
                case 0:
                    EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_INDUSTRY_REFRESH));
                    mBinding.coordinator.setVisibility(View.GONE);
                    mBinding.bidLayout.setVisibility(View.GONE);
                    mBinding.rlError.setVisibility(View.VISIBLE);
                    mBinding.noDataTv.setText(Html.fromHtml("当前数据已下架，请<u><font color='#5892FD'>返回列表</font></u>继续浏览吧~"));
                    mBinding.noDataTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    break;
                case 1:
                    EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_INDUSTRY_REFRESH));
                    mBinding.coordinator.setVisibility(View.GONE);
                    mBinding.bidLayout.setVisibility(View.GONE);
                    mBinding.rlError.setVisibility(View.VISIBLE);
                    mBinding.noDataTv.setText(Html.fromHtml("当前数据已删除，请<u><font color='#5892FD'>返回列表</font></u>继续浏览吧~"));
                    mBinding.noDataTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    break;
                case 2:
                    mBinding.coordinator.setVisibility(View.VISIBLE);
                    mBinding.bidLayout.setVisibility(View.VISIBLE);
                    mBinding.rlError.setVisibility(View.GONE);
                    clickEvent();

                    break;
            }
        });

        mViewModel.ldUserInfo.observe(this, userInfo -> {
            String userNo= SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO,"");//当前用户no
            if (!TextUtils.isEmpty(userInfo.getImAccount())) {
                if(!userNo.equals(userInfo.getNo())) {
                    IMUtils.getInstance().buildSingleTalking(userInfo.getImAccount());
                }else{
                    MToast.showToast(this, "自己不能咨询自己发布的数据");
                }
            } else {
                MToast.showToast(this, "未获取到用户IM账号");
            }
        });

        mViewModel.ldResult.observe(this, result -> {
            if (result.isSuccess()) {
                if (isFouse) {//已关注取消关注
                    isFouse = false;
                    mBinding.imageUserFocus.setImageResource(R.mipmap.merchant_icon_guanzhu);
                    mBinding.tvUserFocus.setText("关注");
                    mBinding.tvUserFocus.setTextColor(getResources().getColor(R.color.color_666666));
                } else {
                    isFouse = true;
                    mBinding.imageUserFocus.setImageResource(R.mipmap.merchant_icon_yiguanzhu);
                    mBinding.tvUserFocus.setText("已关注");
                    mBinding.tvUserFocus.setTextColor(getResources().getColor(R.color.color_secondary_red));
                }
            }
        });
    }


    private void initFragment() {
        fragmentManager = getSupportFragmentManager();
        mInfoFrag= new IndustryInfoFragment();
        mFragment[0]=mInfoFrag;
        dynamicFragment=IndustryDynamicFragment.newInstance(no);
        mFragment[1]=dynamicFragment;
        industryRequireFragment=new IndustryRequireFragment();
        mFragment[2]=industryRequireFragment;
        fragmentManager.beginTransaction().add(R.id.fl_content, mFragment[0]).commitAllowingStateLoss();

        mInfoFrag.setEntity(mEntity);
        industryRequireFragment.setEntity(mEntity);

    }

    @Override
    public void onClick(View v) {
        id = v.getId();
        DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(true);
        mViewModel.getState(no);
    }

    private void clickEvent() {
        if (id == R.id.ll_report || id == R.id.ll_inquire_by_letter ||id == R.id.tv_commit) {
            MToast.showToast(this, "功能开发中，敬请期待");
        } else if (id == R.id.ll_contact_service) {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                return;
            }
            if(mEntity.getCreateUser()!=0) {
                DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
                mViewModel.getImInfo("" + mEntity.getCreateUser());
            }else{
                MToast.showToast(this, "未获取到IM账号");
            }

        } else if (id == R.id.line_user_focus) {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                return;
            }

            DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
            mViewModel.follow(Long.valueOf(no));

        } else if (id == R.id.tv_commit) {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                return;
            }
            boolean personAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
            if (!personAuth) {//去实名
                new RoundDialog.Builder(this)
                        .title("温馨提示")
                        .content("请先进行实名认证")
                        .cancel("我知道了")
                        .confirm("去认证")
                        .cancelable(false)
                        .confirmCallback(v12 -> ARouter.getInstance().build(PathUser.CertificationActivity).withString("type", "1").navigation()).show();
                return;
            }

        } else if (id == R.id.iv_map) {

            if (mEntity != null) {
                ARouter.getInstance().build(PathUser.MapPositionActivity)
                        .withDouble("latitude", mEntity.getAddressLat())
                        .withDouble("longitude", mEntity.getAddressLng())
                        .withString("companyName", mEntity.getParkName())
                        .withString("address", mEntity.getProvinceName() + mEntity.getCityName() + mEntity.getRegionName() + mEntity.getAddressInfo())
                        .navigation();
            }
        }
    }


    public void displayFrg(int index) {
        if (mFragment != null && mFragment[index] != null) {
            if (fragmentManager == null) {
                return;
            }
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            if (!mFragment[index].isAdded()) {
                if (index == currentIndex) {
                    return;
                }
                transaction.hide(mFragment[currentIndex]).add(R.id.fl_content, mFragment[index]).commitAllowingStateLoss();
            } else {
                transaction.hide(mFragment[currentIndex]).show(mFragment[index]).commitAllowingStateLoss();
            }
            currentIndex = index;
        }
    }
    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LoginEvents event) {
        if (event == null) return;
        if (event.getMessageTag() == EventConstant.EVENT_LOGIN) {
            DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
            if(!TextUtils.isEmpty(no))
                mViewModel.getDetail(no);
        }
        EventBus.getDefault().removeStickyEvent(event);
    }
}
